#!/usr/local/bin/perl
# -d:NYTProf
use strict;
use warnings;
use utf8;

use EV;
use JSON::XS;
use Digest::MD5 qw(md5_hex);
require HTTP::Status;
use Time::HiRes qw(gettimeofday);
use Getopt::Long;

use Http qw(HttpCreate);
use Sock qw(SockCreate);
require Chanel;

our %params = (
	debug => 0,
	'http-addr' => '127.0.0.1',
	'sock-addr' => '127.0.0.1',
	'http-port' => 12345,
	'sock-port' => 22345,
	ttl => 120,
	log => "chattest",
#	prof => 1,
);
my @opt = (
	"debug:1",
	"http-addr=s",
	"http-port=i",
	"sock-addr=s",
	"sock-port:i",
	"ttl=i",
	"log=s",
);

# формат ответа
# type=>"response",command=>"login",error=>0
# error = 0 - нет ошибки

eval {
	Start();
};
if($@){
	print "error $@\n";
}
print "Normal exit\n";

################################################

sub Start {

	unless(GetOptions(\%params,@opt)){
		print "param parse error\n";
		return;
	}

	my $HttpWaiter;
	my $SockWaiter;

	if($params{'http-addr'} && $params{'http-port'}){
		unless($HttpWaiter = HttpCreate($params{'http-addr'},$params{'http-port'})){
			return;
		}
	}else{
		print "no http\n";
		return;
	}
	if($params{'sock-addr'} && $params{'sock-port'}){
		unless($SockWaiter = SockCreate($params{'sock-addr'},$params{'sock-port'})){
			return;
		}
	}
	
	binmode STDOUT,":utf8";
	$| = 1;
	
	Chanel::add_chanel("","main",perm=>1,title=>"Общий");
	Chanel::add_chanel("","trade", nolist=>1,perm=>1,title=>"Торговый");
	
	EV::loop;
}
